import type { DataEntityDto } from '@/api/avic/web/DataEntityApi'; // 引入模块DTO
import { saveDataEntity, getDataEntity } from '@/api/avic/web/DataEntityApi'; // 引入模块API
export const emits = ['reloadData', 'close'];
export function useDataEntityForm(props, formType) {
  const { proxy, emit } = getCurrentInstance();
  const form = ref<DataEntityDto>({});
  const formRef = ref(null); // 表单
  const loading = ref(false); // 锁屏
  const rules: Record<string, Rule[]> = {
    secretLevel: [{ required: true, message: '密级不能为空', trigger: 'change' }]
  };
  onMounted(() => {
    if (props.formId) {
      getFormData(props.formId);
    }
  });
  // 编辑、详情页面加载数据
  function getFormData(id) {
    if (!id) {
      return;
    }
    loading.value = true;
    getDataEntity(id)
      .then(async (res) => {
        if (res.success) {
          form.value = res.data;

          loading.value = false;
        }
      })
      .catch(() => {
        proxy.$message.warning('获取表单数据失败！');
        loading.value = false;
      });
  }

  // 保存表单数据
  function saveForm() {
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        // 处理数据
        const postData = proxy.$lodash.cloneDeep(form.value);
        // 发送请求
        saveDataEntity(postData)
          .then((res) => {
            if (res.success) {
              successCallback();
            } else {
              loading.value = false;
            }
          })
          .catch(() => {
            loading.value = false;
          });
      })
      .catch((error) => {
        // 定位校验失败元素
        proxy.$scrollToFirstErrorField(formRef, error);
      });
  }

  // 数据保存成功的回调
  function successCallback() {
    proxy.$message.success('保存成功！');
    emit('reloadData');
    emit('close');
  }

  // 数据保存失败的回调
  function errorCallback() {
    loading.value = false;
  }

  // 返回关闭事件
  function closeModal() {
    emit('close');
  }

  return {
    formRef,
    loading,
    getFormData,
    saveForm,
    successCallback,
    errorCallback,
    closeModal,
    form,
    rules,
    formType
  };
}
